package org.BooCrack.bookstore.pay.controller.admin;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import org.BooCrack.bookstore.common.pojo.BSResult;
import org.BooCrack.bookstore.common.utils.Response;
import org.BooCrack.bookstore.common.utils.ResponseResult;
import org.BooCrack.bookstore.model.dao.custom.CustomMapper;
import org.BooCrack.bookstore.model.entity.Role;
import org.BooCrack.bookstore.model.entity.User;
import org.BooCrack.bookstore.model.service.IRoleService;
import org.BooCrack.bookstore.model.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.ui.Model;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
//@RequestMapping("/admin/user")
@RequestMapping("/admin/V4")
@Api(value = "v1", tags = "8-2.后台管理系统管理用户模块接口")
public class AdminUserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private CustomMapper customMapper;

    @Autowired
    private IRoleService roleService;



    @GetMapping("/user/{userId}")
    @RequiresPermissions("user-edit")
    @ApiOperation(value = "根据id查看用户信息", notes = "根据id查看用户信息")
    public ResponseResult echo(@PathVariable("userId") int userId, Model model){

        User user = userService.findById(userId);
        if(user==null){
            return Response.createFailResp("找不到该用户或该用户不存在！");
        }
        else {
            List<Role> userRoles = customMapper.findRolesByUserId(userId);
            List<Role> allRoles = roleService.findAllRoles();

            Map<String, Object> map = new HashMap<>();
            map.put("user", user);
            map.put("userRoles", userRoles);
            map.put("allRoles", allRoles);

            return Response.createOkResp(map);

        }
    }




    @PutMapping("/user")
    @RequiresPermissions("user-edit")
    @ApiOperation(value = "修改用户信息", notes = "修改用户信息")
    public ResponseResult updateUser(User user, int[] roleIds, Model model){

        User userTemp = userService.findById(user.getUserId());
        if(userTemp==null){
            return Response.createFailResp("找不到该用户或该用户不存在！");
        }
        else {
            BSResult bsResult = userService.updateUser(user);
            //更新用户角色的对应关系
            roleService.updateUserRoleRelationship(user.getUserId(), roleIds);
            return Response.createOkResp(user.getUserId());
        }
    }



    @PostMapping("/user")
    @RequiresPermissions("user-add")
    @ApiOperation(value = "新增用户", notes = "新增用户")
    public ResponseResult<Object> addUser(User user, int[] roleIds){
        BSResult userTemp = userService.checkUserExistByUsername(user.getUsername());
        if(userTemp.getCode()==400){
            return Response.createFailResp("用户已存在！");
        }
        User userFromDB = userService.addUser(user);
        //更新用户角色的对应关系
        roleService.updateUserRoleRelationship(userFromDB.getUserId(),roleIds);
        return Response.createOkResp("添加成功！");
    }



    @DeleteMapping ("/user{userId}")
    @RequiresPermissions("user-delete")
    @ApiOperation(value = "根据id删除用户", notes = "根据id删除用户")
    public ResponseResult delUser(@PathVariable("userId") int userId){
        User userTemp = userService.findById(userId);
        if(userTemp==null){
            return Response.createFailResp("找不到该用户或该用户不存在！");
        }
        else {
            userService.delUser(userId);
            return Response.createOkResp("删除成功！");
        }
    }



    @GetMapping("/user")
    @RequiresPermissions("user-list")
    @ApiOperation(value = "用户列表", notes = "用户列表")
    public ResponseResult userList(Model model){
        try {
            List<User> users = userService.findAllUsers();
            return Response.createOkResp(users);
        }catch(Exception e){
            return Response.createFailResp("查找失败！");
        }
    }





    @PostMapping("/user/role")
    @RequiresPermissions("user-add")
    @ApiOperation(value = "添加角色", notes = "添加角色")
    public ResponseResult toAddition(Model model){
        List<Role> allRoles=roleService.findAllRoles();
        return Response.createOkResp(allRoles);
    }


    @GetMapping("/logout")
    @CacheEvict(cacheNames="authenticationCache",allEntries = true)
    @ApiOperation(value = "注销", notes = "注销")
    public ResponseResult logout() {
        SecurityUtils.getSubject().logout();
        return Response.createOkResp("登出成功！");
    }
}
